//
// Created by yb on 10/21/20.
//
#include <iostream>
#include "Tcptomis.h"

using namespace std;


string misIP = "121.15.171.92" ;
int misPort = 8010 ;

Tcptomis::Tcptomis() = default;

Tcptomis::~Tcptomis() {}


 int Tcptomis::getSockfd(const string &ip , int port){
    struct sockaddr_in serverAddr ;
    memset(&serverAddr,0,sizeof(serverAddr)) ;
    serverAddr.sin_family = PF_INET ;
    serverAddr.sin_addr.s_addr = inet_addr(ip.c_str());
    serverAddr.sin_port = htons(port) ;

    int sockfd = socket(PF_INET, SOCK_STREAM, 0 ) ;
    int ret = connect(sockfd , (struct sockaddr *)&serverAddr ,
                      sizeof(serverAddr));
    if(ret < 0){
        perror("connect to server error : ") ;
        close(sockfd) ;
        return -1 ;
    }
    return sockfd ;
}

 string Tcptomis::submitEcho(const string &msg){
    string result = "" ;
    int buffSize = msg.size()+5 ;
    char *buff = (char*)malloc(buffSize) ;
    int len = msg.length() ;
    memcpy(buff,&len, sizeof(int)) ;
    memcpy(buff+sizeof(int), msg.data(), msg.length()) ;
    int sockfd = getSockfd(misIP, misPort) ;
    int wLen = write(sockfd, buff , msg.length() + 4 ) ;
    if(wLen <= 0){
        perror("send to server error : ") ;
        close(sockfd) ;
        free(buff) ;
        return "" ;
    }
    int recvLen = read(sockfd, buff, buffSize) ;
    memcpy(&len , buff, sizeof(int)) ;
    if(len+5 > buffSize){
        buffSize = len+5 ;
        char *tmp = buff ;
        buff = (char*)realloc(buff , buffSize) ;
        if(!buff){
            free(tmp );
            close(sockfd) ;
            perror("recv from server error : ") ;
            return "" ;
        }
    }
    while(recvLen < len + 4){
        int rLen = read(sockfd, buff+recvLen, buffSize - recvLen) ;
        if(rLen <= 0){
            perror("recv from server error : ") ;
            close(sockfd) ;
            free(buff) ;
            return "" ;
        }
        recvLen += rLen ;
    }
    close(sockfd) ;
    buff[recvLen] = 0 ;
    result = buff+4 ;
    free(buff) ;
    return  result;
}
//int main()
//{
//    cout <<"Hello world!" << endl;
//
//    return 0;
//}
